<template>
    <div>
        <el-card class="xj-table">
            <div class="xj-table-tree">
                <el-card>
                    <avue-tree ref="treeDictionary" :option="treeOption" :data="treeData" @node-click="nodeClick">
                        <template #menu="{node}">
                            <div class="avue-tree__item" v-if="node.data.id !=='0' && node.data.type===1" @click="updRow(node.data,2)"><i class="el-icon-plus"> 添加字典</i></div>
                            <div class="avue-tree__item" v-if="node.data.id !=='0' && node.data.type===2" @click="updRow(node.data,3)"><i class="el-icon-plus"> 添加字典值</i></div>
                            <div class="avue-tree__item" v-if="node.data.id !=='0' && (node.data.type===1 || node.data.type===2 )" @click="generateDict(node.data)"><i class="el-icon-eleme"> 生成枚举</i></div>
                            <div class="avue-tree__item" v-if="node.data.id !=='0' && node.data.type===2" @click="updRow(node.data,4)"><i class="el-icon-edit"> 变更父级</i></div>
                            <div class="avue-tree__item" v-if="node.data.id !=='0'" @click="updRow(node.data,1)"><i class="el-icon-edit"> 编辑</i></div>
                            <div class="avue-tree__item" v-if="node.data.id !=='0'" @click="updRow(node.data,5)"><i class="el-icon-delete"> 删除</i></div>
                            <div class="avue-tree__item" v-if="node.data.id !=='0'" @click="findLeftTree()"><i class="el-icon-refresh"> 刷新</i></div>
                        </template>
                    </avue-tree>
                </el-card>
            </div>
            <div class="xj-table-list">
                <avue-crud ref="crudDict"
                           :data="data"
                           :option="option"
                           v-model:page="page"
                           v-model:search="search"
                           :table-loading="loading"
                           :cell-style="cellStyle"
                           @on-load="onLoad"
                           @refresh-change="onLoad"
                           @search-change="searchChange"
                           @row-click="handleRowClick">
                    <!-- 启用/禁用插槽(默认提供,按需使用) -->
                    <template #disable="{row,index}">
                        <el-switch v-model="row.disable" @change="updDisable(row)"
                                   :active-value=0 :inactive-value=1
                                   active-text="" inactive-text="">
                        </el-switch>
                    </template>

                    <!-- 列表上进行编辑sort -->
                    <template #sort="{row,index}">
                        <el-input v-model="row.sort" @blur="rowSortBlur(row)" placeholder=""></el-input>
                    </template>

                    <!-- 新增父类  -->
                    <template #menu-left="{size}">
                        <span><!--  防抖动--> </span>
                        <el-button type="primary" :size="size" plain icon="el-icon-plus" v-show="rowTreeData.type===undefined" @click="updRow({},0)">目录</el-button>
                        <el-button type="primary" :size="size" plain icon="el-icon-plus" v-show="rowTreeData.type===1" @click="updRow(rowTreeData,2)">字典</el-button>
                        <el-button type="primary" :size="size" plain icon="el-icon-plus" v-show="rowTreeData.type===2" @click="updRow(rowTreeData,3)">字典值</el-button>
                    </template>

                    <template #menu="{scope,row,size,index}">
                        <el-button type="primary" :size="size" text icon="el-icon-edit" @click="updRow(row,1)">编辑</el-button>
                        <el-button type="primary" :size="size" text icon="el-icon-delete" @click="rowDel(row,index)">删除</el-button>
                    </template>
                </avue-crud>
            </div>
        </el-card>

        <!-- 弹层 -->
        <el-dialog draggable :title="rowData!=null && rowData.name?('在- ['+ rowData.name + '] -下'+ (rowData.type===1?'新增字典':'新增字典值')) :'新增目录'"
                   v-if="addDialogVisible"
                   v-model="addDialogVisible"
                   :width="dialogWidth"
                   top="6vh"
                   @close="closeDialog">
            <Add @closeDialog="closeDialog" :uri="uri" :rowData="rowData"></Add>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
        <el-dialog draggable :title="'编辑 -- '+rowData.name"
                   v-if="updDialogVisible"
                   v-model="updDialogVisible"
                   :width="dialogWidth"
                   top="6vh"
                   @close="closeDialog">
            <Upd @closeDialog="closeDialog" :uri="uri" :rowData="rowData"></Upd>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
        <el-dialog draggable :title="'变更父级 -- '+rowData.name"
                   adminDictionary.vue
                   v-if="updPidDialogVisible"
                   v-model="updPidDialogVisible"
                   width="35%"
                   top="6vh"
                   @close="closeDialog">
            <AdminDictionaryPid @closeDialog="closeDialog" :uri="uri" :rowData="rowData"></AdminDictionaryPid>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
        <el-dialog draggable title="预览"
                   v-if="generateDictDialogVisible"
                   v-model="generateDictDialogVisible"
                   :width="dialogWidth"
                   top="6vh"
                   @close="closeDialog">
            <GenerateDict @closeDialog="closeDialog" :generateDictData="generateDictData"></GenerateDict>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
    </div>
</template>


<script>

import {defineAsyncComponent} from 'vue';

export default {
    components: {
        Add: defineAsyncComponent(() => import('./dictionaryAdd.vue')),
        Upd: defineAsyncComponent(() => import('./dictionaryUpd.vue')),
        GenerateDict: defineAsyncComponent(() => import('./generateDictPreview.vue')), //生成js/枚举类预览
        AdminDictionaryPid: defineAsyncComponent(() => import('./dictionaryPid.vue')) //变更父级
    },
    data() {
        return {
            treeOption: JSON.parse(JSON.stringify(this.website.treeOption)),
            treeData: [],
            uri: {
                infoList: "/api/admin/sys/dictionary/tree",
                info: "/api/admin/sys/dictionary",
                generateEnum: "/api/admin/sys/dictionary/generateEnum",
                updPidInfoList: "/api/admin/sys/dictionary/tree",
            },
            loading: true,
            dialogWidth: "60%",
            addDialogVisible: false,
            updDialogVisible: false,
            updPidDialogVisible: false,
            generateDictDialogVisible: false,
            page: this.website.pageParams,
            search: {}, //
            data: [],
            rowData: {},
            option: {},
            // dictOneDict: [], // 一级选择数据
            // dictTwoDict: [], // 二级选择数据
            // dictThreeDict: [], // 三级选择数据
            rowTreeData: {}, // 当前左侧选中数据
            generateDictData: [], // 生成枚举数据
        }
    },
    mounted() {

        this.option = JSON.parse(JSON.stringify(this.website.optionConfig));

        //this.option.menu = false
        this.option.defaultExpandAll = true;
        this.option.index = false;
        this.option.rowKey = "id";
        //this.option. = "id"
        this.option.height = 600;
        this.option.treeProps = {
            children: 'dictList'
        };
        this.option.column = [
            {
                label: '字典名称',
                prop: 'name',
                search: false,
                overHidden: true,
            },
            {
                label: '字典Code',
                prop: 'code',
                search: false,
                overHidden: true,
            },
            {
                label: '描叙',
                prop: 'desc',
                search: false,
                overHidden: true,
            },

            {
                label: '扩展1',
                prop: 'ext1',
                search: false,
                overHidden: true,
            },
            {
                label: '扩展2',
                prop: 'ext2',
                search: false,
                overHidden: true,
            },
            {
                label: '扩展3',
                prop: 'ext3',
                search: false,
                overHidden: true,
            },
            {
                label: '排序',
                prop: 'sort',
                search: false,
                overHidden: true,
            },
            {
                label: '禁用/启用',
                prop: 'disable',
                search: false,
                overHidden: true,
            },
        ]
    },
    created() {
        // 1、左侧菜单配置
        this.treeOption.props.label = "name";
        this.treeOption.props.children = "children";
        this.treeOption.menu = true;
        // 查询左侧菜单数据
        this.findLeftTree();
    },
    // 被 keep-alive 缓存的组件激活时调用, crudDoLayout为防止表格错乱
    activated: function () {
        this.crud.doLayout(this, this.$refs.crudDict)
    },
    methods: {
        onLoad() {
            this.search.code = this.rowTreeData.code;
            // 开始查询
            this.crud.list(this, false).then((res) => {
                this.crud.doLayout(this, this.$refs.crudDict)
            });
        },
        searchChange(done) {
            this.page.currentPage = 1;
            this.onLoad();
            done();
        },
        /**
         * 查询左侧 字典数据
         */
        findLeftTree() {
            this.crud.get(this.uri.infoList).then((res) => {
                this.treeData = res.data.data;
                // 添加查询全部
                this.treeData.unshift({id: "0", pid: '0', name: '目录'})

                // 设置默认选中和自动展开
                if (this.rowTreeData.id != null && this.rowTreeData.id !== '') {
                    this.treeOption.defaultExpandedKeys = [this.rowTreeData.id];
                    this.$nextTick(() => {
                        this.$refs.treeDictionary.setCurrentKey(this.rowTreeData.id);
                    })
                }
            });
        },
        closeDialog(isRefresh, dataId) {
            this.addDialogVisible = false;
            this.updDialogVisible = false;
            this.generateDictDialogVisible = false;
            this.updPidDialogVisible = false;
            this.rowData = {};
            if (isRefresh != null && isRefresh) {
                this.onLoad();
            }
            // 左侧树结构数据更新
            if (dataId != null && dataId) {
                this.rowTreeData.id = dataId
                this.findLeftTree();
            }
        },
        // 行编辑
        updRow(row, type) {
            this.rowData = row;
            switch (type) {
                case 0:
                    // 新增顶级（目录）
                    this.rowData = null;
                    this.addDialogVisible = true;
                    break;
                case 1:
                    // 编辑
                    this.updDialogVisible = true;
                    break;
                case 2:
                    // +字典
                    if (Object.keys(row).length === 0 || row.type !== 1) {
                        this.$message.error('请先目录下添加字典');
                        break;
                    } else {
                        this.addDialogVisible = true;
                        break;
                    }
                case 3:
                    // +字典值
                    if (Object.keys(row).length === 0 || row.type !== 2) {
                        this.$message.error('请先左侧选中字典后在添加字典值');
                        break;
                    } else {
                        this.addDialogVisible = true;
                        break;
                    }
                case 4:
                    // 变更父级
                    this.updPidDialogVisible = true;
                    break;
                case 5:
                    // 删除(左边树上删除)
                    this.rowDel(row);
                    break;
                default:
                    this.$message.error('操作类型错误');
                    break;
            }
        },
        // 行删除
        rowDel(row) {
            this.$confirm('此操作将永久删除【' + row.name + '】以及子数据,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.crud.del(this.uri.info + "/" + row.id).then(() => {
                    // 删除后展示父级
                    // this.rowTreeData.id = row.pid;
                    // this.rowTreeData.code = "";
                    // 判断删除对象是否是当前左侧菜单选中对象,如果是删除后清除左侧菜单选中对象
                    if (row.id === this.rowTreeData.id) {
                        this.rowTreeData = {}
                    }
                    // 删除后刷新列表数据
                    this.onLoad();
                    // 更新树结构数据
                    this.$refs.treeDictionary.remove(row.id)
                })
            })
        },

        // 排序
        rowSortBlur(row) {
            if (row.id != null && this.rowData.sort != row.sort) {
                this.crud.put(this.uri.info + "/" + row.id, row);
            }
        },
        // 启用/禁用
        updDisable(row) {
            if (row.id != null) {
                this.crud.put(this.uri.info + "/" + row.id, row);
            }
        },
        handleRowClick(row) {
            this.rowData = JSON.parse(JSON.stringify(row));
            //this.rowData = row;
        },
        cellStyle({row, column}) {
            if (column.property == "disable") {
                // fontWeight: 'bold',fontSize: '20'
                return row.disable == 0 ? {color: 'green'} : {color: 'red'}
            }
        },
        handleChange(form) {
            this.$message.success(JSON.stringify(form))
        },
        //验证字符串是否是数字
        checkNumber(theObj) {
            var reg = /^[0-9]+.?[0-9]*$/;
            if (reg.test(theObj)) {
                return true;
            }
            return false;
        },
        // 生成枚举
        generateDict(row) {
            this.crud.get(this.uri.generateEnum, {pid: row.id}).then((res) => {
                if (res.data.code === 200) {
                    this.generateDictDialogVisible = true;
                    this.generateDictData = res.data.data;
                }
            })
        },
        /**
         * 点击左菜单重置右菜单数据
         * @param data
         */
        nodeClick(data) {
            this.rowTreeData = data;
            this.search.pid = data.id;
            this.onLoad();
        }
    }
}
</script>
<style>
</style>
